[Python进阶-4]类的继承/多态/多重继承/任意多参数 |
您所在的位置:网站首页 › python 多个参数传递 › [Python进阶-4]类的继承/多态/多重继承/任意多参数 |
(1)类的继承 ——需要用super(subclass,self).init(args)继承父类的属性。后面的init里的self不必传递,因为super()里意境传递多,会隐式传递过去。 class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender class Teacher(Person): def __init__(self, name, gender, course): super(Teacher,self).__init__(name,gender) self.course=course t = Teacher('Alice', 'Female', 'English') print t.name print t.course(2)验证某变量属于某类,可以用isinstance,以下是用“实例是否属于某类”,同样可以用作“某变量是否是str”等验证。 class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender class Student(Person): def __init__(self, name, gender, score): super(Student, self).__init__(name, gender) self.score = score class Teacher(Person): def __init__(self, name, gender, course): super(Teacher, self).__init__(name, gender) self.course = course t = Teacher('Alice', 'Female', 'English') print isinstance(t,Person) print isinstance(t,Student) print isinstance(t,Teacher) print isinstance(t,object)(3)多态。简单理解就是一个东西可以根据给的参数不同变现出不同结果。在这里,一般是指父类子类等都具有同一个方法(输出结果不同),此时,调用不同类的方法则结果不同。 ——首先是因为调用实例方法的时候,不看类型,只看实例有没有这个方法,有就行,如下: ——其次,是不管是子类父类,调用时,一般是先找自己有无这个方法,如没有再向上继承的找。 import json class Students(object): def read(self): return r'["Tim", "Bob", "Alice"]' s = Students() print json.load(s)(4) 多重继承: class Person(object): pass class Student(Person): pass class Teacher(Person): pass class SkillMixin(object): pass class BasketballMixin(SkillMixin): def skill(self): return 'basketball' class FootballMixin(SkillMixin): def skill(self): return 'football' class BStudent(Student,BasketballMixin): pass class FTeacher(Teacher,FootballMixin): pass s = BStudent() print s.skill() t = FTeacher() print t.skill()(5) 任意多参数,用**kw: class Person(object): def __init__(self, name, gender,**kw): self.name=name self.gender=gender for k,v in kw.iteritems(): setattr(self,k,v) p = Person('Bob', 'Male', age=18, course='Python') print p.age print p.course |
今日新闻 |
点击排行 |
|
推荐新闻 |
|
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |